package models

import (
	"gorm.io/gorm"
	"learn-srv/basic/config"
	"time"
)

type Course struct {
	gorm.Model
	UserId    int        `json:"user_id" gorm:"type:int;comment:'用户id'"`
	Title     string     `json:"title" gorm:"type:varchar(50);comment:'课程名称'"`
	Price     float64    `json:"price" gorm:"type:decimal(10,2);comment:'课程价格"`
	Desc      string     `json:"desc" gorm:"type:varchar(300);comment:'描述'"`
	Stock     int        `json:"stock" gorm:"type:int;comment:'库存'"`
	StartTime *time.Time `json:"start_time" gorm:"type:datetime;comment:'开始时间'"`
	EndTime   *time.Time `json:"end_time" gorm:"type:datetime;comment:'结束时间'"`
	Status    int        `json:"status" gorm:"type:int;comment:'状态 1-未开始 2-已开始 3-已结束'"`
}

func (c *Course) TableName() string {
	return "course"
}

func (c *Course) CreateCourse() error {
	return config.DB.Create(&c).Error
}

func (c *Course) GetCourseInfo(id int) error {
	return config.DB.Model(&Course{}).Where("id = ?", id).Limit(1).Find(&c).Error
}

// 扣减库存
func (c *Course) DelCourseStock(id, num int) error {
	return config.DB.Model(&Course{}).Where("id = ?", id).Update("stock", gorm.Expr("stock - ?", num)).Find(&c).Error
}
